import QtQuick
import QtQuick.Controls
import Fk
import Fk.Widgets as W

W.PageBase {
    id: root
    
    property var gameData: ({ 
        phase: "recruit", 
        players: [],
        currentPlayer: null,
        turn: 1
    })
    
    // 背景 - 三国风格
    Image {
        anchors.fill: parent
        source: "packages/wenhe_yanbing/Fk/Assets/background.jpg"
        fillMode: Image.PreserveAspectCrop
    }
    
    // 右侧玩家列表（可收起）
    Rectangle {
        id: playerListPanel
        width: playerListCollapsed ? 50 : 220
        height: parent.height
        anchors.right: parent.right
        color: "#8B4513"
        opacity: 0.9
        border.color: "#DAA520"
        border.width: 2
        
        property bool playerListCollapsed: false
        
        // 展开/收起按钮
        Button {
            id: togglePlayerList
            anchors.top: parent.top
            anchors.right: parent.right
            width: 30
            height: 30
            text: playerListPanel.playerListCollapsed ? "▶" : "◀"
            onClicked: playerListPanel.playerListCollapsed = !playerListPanel.playerListCollapsed
        }
        
        // 玩家列表内容
        Column {
            anchors {
                top: togglePlayerList.bottom
                left: parent.left
                right: parent.right
                bottom: parent.bottom
                margins: 5
            }
            visible: !playerListPanel.playerListCollapsed
            spacing: 5
            
            Text {
                text: "玩家列表"
                color: "white"
                font.pixelSize: 16
                font.bold: true
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            ListView {
                width: parent.width
                height: parent.height - 30
                model: root.gameData.players ? root.gameData.players.sort((a, b) => b.health - a.health) : []
                delegate: Rectangle {
                    width: parent.width
                    height: 60
                    color: modelData.isCurrent ? "#FFD700" : (index % 2 == 0 ? "#A0522D" : "#8B4513")
                    radius: 5
                    border.color: getKingdomColor(modelData.kingdom)
                    border.width: 2
                    
                    Column {
                        anchors.centerIn: parent
                        spacing: 2
                        
                        Text {
                            text: modelData.name
                            color: "white"
                            font.pixelSize: 12
                            font.bold: true
                            width: parent.width - 10
                            elide: Text.ElideRight
                        }
                        
                        Text {
                            text: "❤️ " + modelData.health
                            color: modelData.health < 10 ? "#FF0000" : "#00FF00"
                            font.pixelSize: 11
                        }
                        
                        Text {
                            text: "等级 " + modelData.tavernTier + " | " + getKingdomText(modelData.kingdom)
                            color: "#FFD700"
                            font.pixelSize: 10
                        }
                    }
                }
            }
        }
    }
    
    // 左下角 - 货币信息
    Rectangle {
        id: currencyPanel
        width: 150
        height: 80
        anchors {
            left: parent.left
            bottom: parent.bottom
            margins: 10
        }
        color: "#8B4513"
        opacity: 0.9
        radius: 10
        border.color: "#DAA520"
        border.width: 2
        
        Column {
            anchors.centerIn: parent
            spacing: 5
            
            Row {
                spacing: 10
                Image {
                    source: "packages/wenhe_yanbing/Fk/Assets/coin.png"
                    width: 20
                    height: 20
                }
                Text {
                    text: " × " + (root.gameData.currentPlayer ? root.gameData.currentPlayer.gold : 0)
                    color: "#FFD700"
                    font.pixelSize: 18
                    font.bold: true
                }
            }
            
            Row {
                spacing: 10
                Text {
                    text: "❤️"
                    color: "#FF0000"
                    font.pixelSize: 16
                }
                Text {
                    text: " " + (root.gameData.currentPlayer ? root.gameData.currentPlayer.health : 0)
                    color: "white"
                    font.pixelSize: 16
                    font.bold: true
                }
            }
            
            Text {
                text: "回合: " + root.gameData.turn
                color: "white"
                font.pixelSize: 14
            }
        }
    }
    
    // 右下角 - 玩家信息
    Rectangle {
        id: playerInfoPanel
        width: 180
        height: 100
        anchors {
            right: playerListPanel.left
            bottom: parent.bottom
            margins: 10
        }
        color: "#8B4513"
        opacity: 0.9
        radius: 10
        border.color: getKingdomColor(root.gameData.currentPlayer ? root.gameData.currentPlayer.kingdom : "qun")
        border.width: 2
        
        Column {
            anchors.centerIn: parent
            spacing: 8
            
            Text {
                text: root.gameData.currentPlayer ? root.gameData.currentPlayer.name : "玩家"
                color: "white"
                font.pixelSize: 16
                font.bold: true
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "势力: " + getKingdomText(root.gameData.currentPlayer ? root.gameData.currentPlayer.kingdom : "qun")
                color: getKingdomColor(root.gameData.currentPlayer ? root.gameData.currentPlayer.kingdom : "qun")
                font.pixelSize: 14
            }
            
            Text {
                text: "酒馆等级: " + (root.gameData.currentPlayer ? root.gameData.currentPlayer.tavernTier : 1)
                color: "#FFD700"
                font.pixelSize: 14
            }
        }
    }
    
    // 底部 - 手牌区域
    Rectangle {
        id: handArea
        height: 140
        anchors {
            left: parent.left
            right: playerListPanel.left
            bottom: parent.bottom
            margins: 10
        }
        color: "transparent"
        
        Text {
            anchors.left: parent.left
            anchors.top: parent.top
            text: "手牌 (" + (root.gameData.currentPlayer ? root.gameData.currentPlayer.hand.length : 0) + ")"
            color: "white"
            font.pixelSize: 14
            font.bold: true
        }
        
        ListView {
            anchors {
                top: parent.top
                bottom: parent.bottom
                left: parent.left
                right: parent.right
                topMargin: 25
            }
            orientation: ListView.Horizontal
            spacing: 10
            
            model: root.gameData.currentPlayer ? root.gameData.currentPlayer.hand : []
            
            delegate: MinionCard {
                width: 100
                height: 120
                minionData: modelData
                isHand: true
                onClicked: {
                    ClientInstance.notifyServer("PushRequest", {
                        command: "WenheYanbing.RecruitMinion",
                        data: { action: "place", handIndex: index }
                    })
                }
            }
        }
    }
    
    // 中间 - 战场区域
    Rectangle {
        id: battlefield
        anchors {
            top: phaseSpecificArea.bottom
            bottom: handArea.top
            left: parent.left
            right: playerListPanel.left
            margins: 10
        }
        color: "transparent"
        
        Text {
            anchors.left: parent.left
            anchors.top: parent.top
            text: "战场 (" + (root.gameData.currentPlayer ? root.gameData.currentPlayer.board.length : 0) + "/7)"
            color: "white"
            font.pixelSize: 16
            font.bold: true
        }
        
        Grid {
            anchors.centerIn: parent
            columns: 4
            spacing: 15
            
            Repeater {
                model: root.gameData.currentPlayer ? root.gameData.currentPlayer.board : []
                
                delegate: MinionCard {
                    width: 110
                    height: 140
                    minionData: modelData
                    isOnBoard: true
                    onClicked: {
                        ClientInstance.notifyServer("PushRequest", {
                            command: "WenheYanbing.RecruitMinion", 
                            data: { action: "sell", boardPosition: index }
                        })
                    }
                }
            }
            
            // 空位指示器
            Repeater {
                model: 7 - (root.gameData.currentPlayer ? root.gameData.currentPlayer.board.length : 0)
                
                delegate: Rectangle {
                    width: 110
                    height: 140
                    color: "transparent"
                    border.color: "#8B4513"
                    border.width: 2
                    radius: 8
                    
                    Text {
                        text: "空位"
                        color: "#8B4513"
                        font.pixelSize: 14
                        anchors.centerIn: parent
                    }
                }
            }
        }
    }
    
    // 顶部 - 阶段特定区域
    Rectangle {
        id: phaseSpecificArea
        height: 220
        anchors {
            top: parent.top
            left: parent.left
            right: playerListPanel.left
            margins: 10
        }
        color: "transparent"
        
        Loader {
            anchors.fill: parent
            sourceComponent: root.gameData.phase === "recruit" ? shopComponent : combatTopComponent
        }
    }
    
    // 商店组件（招募阶段）
    Component {
        id: shopComponent
        
        Column {
            anchors.fill: parent
            spacing: 10
            
            Text {
                text: "🛒 随从商店 (等级 " + (root.gameData.currentPlayer ? root.gameData.currentPlayer.tavernTier : 1) + ")"
                color: "#FFD700"
                font.pixelSize: 18
                font.bold: true
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 20
                
                // 商店操作按钮
                Column {
                    spacing: 8
                    
                    Button {
                        text: "升级酒馆\n(" + (root.gameData.currentPlayer ? root.gameData.currentPlayer.upgradeCost : 0) + "💰)"
                        width: 100
                        height: 60
                        enabled: root.gameData.currentPlayer && root.gameData.currentPlayer.gold >= root.gameData.currentPlayer.upgradeCost
                        onClicked: {
                            ClientInstance.notifyServer("PushRequest", {
                                command: "WenheYanbing.RecruitMinion",
                                data: { action: "levelup" }
                            })
                        }
                    }
                    
                    Button {
                        text: "刷新商店\n(1💰)"
                        width: 100
                        height: 40
                        enabled: root.gameData.currentPlayer && root.gameData.currentPlayer.gold >= 1
                        onClicked: {
                            ClientInstance.notifyServer("PushRequest", {
                                command: "WenheYanbing.RecruitMinion", 
                                data: { action: "refresh" }
                            })
                        }
                    }
                    
                    Button {
                        text: root.gameData.currentPlayer && root.gameData.currentPlayer.freezeTavern ? "取消冻结" : "冻结商店"
                        width: 100
                        height: 40
                        onClicked: {
                            ClientInstance.notifyServer("PushRequest", {
                                command: "WenheYanbing.RecruitMinion", 
                                data: { action: "freeze" }
                            })
                        }
                    }
                }
                
                // 商店中的随从
                Row {
                    spacing: 15
                    
                    Repeater {
                        model: root.gameData.currentPlayer ? root.gameData.currentPlayer.tavernMinions : []
                        
                        delegate: MinionCard {
                            width: 100
                            height: 140
                            minionData: modelData
                            isInShop: true
                            onClicked: {
                                ClientInstance.notifyServer("PushRequest", {
                                    command: "WenheYanbing.RecruitMinion",
                                    data: { action: "buy", tavernIndex: index }
                                })
                            }
                        }
                    }
                }
            }
            
            // 三连奖励
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 10
                visible: root.gameData.currentPlayer && root.gameData.currentPlayer.tripleRewards.length > 0
                
                Text {
                    text: "三连奖励:"
                    color: "#FFD700"
                    font.pixelSize: 14
                    anchors.verticalCenter: parent.verticalCenter
                }
                
                Repeater {
                    model: root.gameData.currentPlayer ? root.gameData.currentPlayer.tripleRewards : []
                    
                    delegate: MinionCard {
                        width: 100
                        height: 140
                        minionData: modelData
                        onClicked: {
                            ClientInstance.notifyServer("PushRequest", {
                                command: "WenheYanbing.RecruitMinion",
                                data: { action: "claim", rewardIndex: index }
                            })
                        }
                    }
                }
            }
        }
    }
    
    // 战斗阶段顶部组件
    Component {
        id: combatTopComponent
        
        Column {
            anchors.fill: parent
            spacing: 10
            
            // 左上角 - 对手信息
            Rectangle {
                width: 200
                height: 60
                color: "#8B4513"
                opacity: 0.9
                radius: 8
                border.color: "#FF0000"
                border.width: 2
                
                Column {
                    anchors.centerIn: parent
                    spacing: 3
                    
                    Text {
                        text: "对手: " + (root.gameData.opponent ? root.gameData.opponent.name : "")
                        color: "white"
                        font.pixelSize: 14
                        font.bold: true
                    }
                    
                    Text {
                        text: "势力: " + getKingdomText(root.gameData.opponent ? root.gameData.opponent.kingdom : "qun")
                        color: getKingdomColor(root.gameData.opponent ? root.gameData.opponent.kingdom : "qun")
                        font.pixelSize: 12
                    }
                    
                    Text {
                        text: "生命: " + (root.gameData.opponent ? root.gameData.opponent.health : 0)
                        color: "#FF0000"
                        font.pixelSize: 12
                    }
                }
            }
            
            // 中间 - 对手战场
            Text {
                text: "对手战场"
                color: "#FF6B6B"
                font.pixelSize: 16
                font.bold: true
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Repeater {
                    model: root.gameData.opponent ? root.gameData.opponent.board : []
                    
                    delegate: MinionCard {
                        width: 100
                        height: 140
                        minionData: modelData
                        isOpponent: true
                    }
                }
            }
            
            // 战斗日志
            Rectangle {
                width: 300
                height: 80
                anchors.horizontalCenter: parent.horizontalCenter
                color: "transparent"
                border.color: "#444"
                
                ListView {
                    anchors.fill: parent
                    model: root.gameData.combatLog
                    delegate: Text {
                        text: modelData
                        color: "#CCC"
                        font.pixelSize: 10
                        width: parent.width
                        wrapMode: Text.Wrap
                    }
                    ScrollBar.vertical: ScrollBar {}
                }
            }
        }
    }
    
    // 势力颜色映射
    function getKingdomColor(kingdom) {
        switch(kingdom) {
            case "wei": return "#1E90FF";
            case "shu": return "#FF4500";
            case "wu": return "#32CD32";
            case "qun": return "#8A2BE2";
            default: return "#FFFFFF";
        }
    }
    
    function getKingdomText(kingdom) {
        switch(kingdom) {
            case "wei": return "魏";
            case "shu": return "蜀"; 
            case "wu": return "吴";
            case "qun": return "群";
            default: return "未知";
        }
    }

    function handleMessage(command, data) {
        switch(command) {
            case "WenheYanbing.UpdatePhase":
                root.gameData.phase = data.phase;
                break;
            case "WenheYanbing.RecruitPhase":
                root.gameData.phase = "recruit";
                root.gameData.turn = data.turn;
                break;
            case "WenheYanbing.CombatPhase":
                root.gameData.phase = "combat";
                root.gameData.turn = data.turn;
                break;
            case "WenheYanbing.CombatResult":
                root.gameData.combatLog = data.log;
                root.gameData.opponent = data.opponent;
                break;
        }
    }
    
    Component.onCompleted: {
        // 注册回调
        ClientInstance.addCallback("WenheYanbing.UpdatePhase", handleMessage);
        ClientInstance.addCallback("WenheYanbing.RecruitPhase", handleMessage);
        ClientInstance.addCallback("WenheYanbing.CombatPhase", handleMessage);
        ClientInstance.addCallback("WenheYanbing.CombatResult", handleMessage);
    }
}